
import * as actions from './';
import HttpRequest from './../common/http';

const rootUrl = window.restConfig.rootUrl;
  
  
export const initRecords = (code) => {
  return (dispatch) => {

    HttpRequest.get(rootUrl + '/personal/records/'+code)
      .then((ret) => {
        dispatch({
          type: actions.COURSE_RECORD_CHANGE,
          data: ret.data
        })
      }).catch((err) => {
        dispatch(showError('加载数据失败'));
      });
  }
}

export const moreRecords = () => {
  return (dispatch,getStore) => {
    let state = getStore().courseRecord || {};
    HttpRequest.get(rootUrl + '/personal/more/records')
      .then((ret) => {
        let newData = state.data;
        let keys = (ret.data&&ret.data.data&&Object.keys(ret.data.data)) || [];
        keys.forEach( (key) => {
          if (newData[key]) {
            newData[key] = newData[key].concat(ret.data.data[key]);
          } else {
            newData[key] = ret.data.data[key];
          }
        })
        dispatch({
          type: actions.COURSE_RECORD_CHANGE,
          data: {
            data: newData
          }
        })
        dispatch({
          type: actions.COURSE_RECORD_CHANGE,
          data: {
            page: ret.data.page
          }
        })
      }).catch((err) => {
        dispatch(showError('加载数据失败'));
      });
  }
}

export const dataChange = (name, value) => {
  return {
    type: actions.COURSE_RECORD_CHANGE,
    data: {
      data: {
        [name]: value
      }
    }
  }
}

export const stateChange = (name, value) => {
  return {
    type: actions.COURSE_RECORD_CHANGE,
    data: {
      state: {
        [name]: value
      }
    }
  }
}
export const errorChange = (name, value) => {
  return {
    type: actions.COURSE_RECORD_CHANGE,
    data: {
      error: {
        [name]: value
      }
    }
  }
}

export const showError = (text) => {
  return (dispatch) => {
    dispatch(errorChange('hasError', true));
    dispatch(errorChange('msg', text));

    let timer = setTimeout( () => {
      window.clearTimeout(timer);
      dispatch(errorChange('hasError', false));
      dispatch(errorChange('msg', ''));
    }, 2000);
  }
}
//   export const getCourseRecord = (id) => { // 先这样写上
//     return (dispatch) => {
//       HttpRequest.get(rootUrl + '/course/record/'+id)
//         .then((ret) => {
//           if(ret.code === 10000){
//             dispatch({
//               type: actions.COURSE_RECORD_CHANGE,
//               data: {
//                 state: ret.data || {}
//               }
//             })
//           }
//         }).catch((err) => {
//           dispatch({
//             type: actions.COURSE_RECORD_CHANGE,
//             data: err.message
//           }) 
//         });
//     }
//   }

